package com.mall.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mall.common.RedisPool;

import redis.clients.jedis.Jedis;

public class RedisPoolUtil {
	
	
	private static Logger log = LoggerFactory.getLogger(RedisPoolUtil.class);
	
	
	//设置
	public static String set(String key ,String value){
		
		Jedis jedis = null;
		String result = null;
		
		try {
			jedis = RedisPool.getJedis();
			result = jedis.set(key, value);
		} catch (Exception e) {
			//注意, 异常信息不需要有占位符
			log.error("set key: {} , value: {} ,  error:",key,value,e);
			jedis.close();
			return result;
		}
		jedis.close();
		return result;
		
	} 
	
	//得到值
	public static String get(String key){
		
		Jedis jedis = null;
		String result = null;
		
		try {
			jedis = RedisPool.getJedis();
			result = jedis.get(key);
		} catch (Exception e) {
			//注意, 异常信息不需要有占位符
			log.error("get key: {}  error:",key,e);
			jedis.close();
			return result;
		}
		jedis.close();
		return result;
		
	} 
	
	//删除键
	public static Long del(String key){
		
		Jedis jedis = null;
		Long result = null;
		
		try {
			jedis = RedisPool.getJedis();
			result = jedis.del(key);
		} catch (Exception e) {
			//注意, 异常信息不需要有占位符
			log.error("del key: {}  error:",key,e);
			jedis.close();
			return result;
		}
		jedis.close();
		return result;
		
	} 
	
	//设置键的同时设置过期时间
	public static String setEx(String key,String value,int seconds){
		
		Jedis jedis = null;
		String result = null;
		
		try {
			jedis = RedisPool.getJedis();
			result = jedis.setex(key, seconds, value);
		
		} catch (Exception e) {
			//注意, 异常信息不需要有占位符
			log.error("setExire key: {} error: ",key,e);
			jedis.close();
			return result;
		}
		jedis.close();
		return result;
		
	} 
	
	//设置过期时间 , 单位是秒
	public static Long expire(String key,int seconds){
		
		Jedis jedis = null;
		Long result = null;
		
		try {
			jedis = RedisPool.getJedis();
			result = jedis.expire(key, seconds);
		} catch (Exception e) {
			//注意, 异常信息不需要有占位符
			log.error("expire key: {} error:",key,e);
			jedis.close();
			return result;
		}
		jedis.close();
		return result;
		
	} 
	
	
	//测试
	public static void main(String[] args) {
		
		RedisPoolUtil.set("one", "meng");
		
		String result = RedisPoolUtil.get("one");
		
		RedisPoolUtil.setEx("two", "havaExpire", 100);
		
		RedisPoolUtil.expire("two", 200 );
		
		RedisPoolUtil.del("two");
	}
	
}
